<?php
namespace App\Models\Account;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Input;


class RemainByNewUserLoginModel extends  Model{

	protected $table='retain_new';
    protected $_db_select = '';

	public function paginate()
    {
        
        
    	$perPage = Request::get('per_page', 10);

        $page = Request::get('page', 1);
        
        $start = ($page-1)*$perPage;

        $qdCond = RemainByNewUserLoginModel::remainChartDate(['start'=>Request::get('start'), 'end' =>Request::get('end')]);
        \Log::debug(__METHOD__, [$this->selectdb(),$qdCond,\Config::get("database.connections.remote_bgsi")]);
        $tableAccount = 'retain_new';
        //$offset = ($page - 1) * $perPage;
        //$limit = $perPage;

        //$sql = "SELECT * FROM tb_new_user_login ORDER BY id DESC limit $offset, $limit";
        $rw = \DB::connection($this->selectdb())->table($tableAccount);

        // 自定义时间查询
        if (isset($qdCond['start'])) {
            //$rw->where('reg_time', '>=', "0");
            $rw->whereRaw("retain_time >= '{$qdCond['start']}'");
        }

        if (isset($qdCond['end'])) {
            //$rw->where('reg_time', '<=', "{$qdRond['end']}");
            $rw->whereRaw("retain_time <= '{$qdCond['end']}'");
        }
        //$result = \DB::connection($this->selectdb())->select($sql);

        $rw->orderBy('id', 'DESC');
        $rw->skip($page* $perPage - $perPage)->take($perPage);
        $result = $rw->get();

        \Log::debug('remain source data', [$qdCond, $rw->toSql(), $rw->getBindings()]);

        $result = $result->toArray();

        $total = $rw->count();

        $list = static::hydrate($result);

        $paginator = new LengthAwarePaginator($list, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }

    public static function with($relations)
    {
        return new static;
    }


    public function selectdb(){
        if ($this->_db_select) {
            return $this->_db_select;
        }
        //\App\Models\Area::RemoteBgsiSelectByArea(Input::get('area'));
        $this->_db_select = 'mysql_statistic';
        return $this->_db_select;
    }

    // public function getConnectionName(){
        
    //     return $this->selectdb();
    // }

    public function where()
    {
        //\Log::debug(__METHOD__, [\Config::get("database.connections.remote_bgsi")]);
        $this->query = parent::where(...func_get_args());
        return $this;
    }

    public function remainChart($cond = []){
        
        list($start, $end) = array_values($this->remainChartDate($cond));        

        $tableAccount = 'new_user_login';
        $data = \DB::connection($this->selectdb())->table($tableAccount)->whereBetween('reg_time',[$start, $end])->get();
        $data = $data->toArray();
//exit(print_r([$data, $map],1));        
        $newData = [];
        foreach($data as $item) {
            $item = (array)$item;
            $newData['retain_num'] += $item['retain_num'];
            $newData['day1'] += $item['day1'];
            $newData['day2'] += $item['day2'];
            $newData['day3'] += $item['day3'];
            $newData['day4'] += $item['day4'];
            $newData['day5'] += $item['day5'];
            $newData['day6'] += $item['day6'];
            $newData['day7'] += $item['day7'];
            $newData['day14'] += $item['day14'];
            $newData['day30'] += $item['day30'];
        }
        
        foreach($newData as $attr=> $val) {
            
            if ('reg_num' == $attr) {
                continue;
            }
            
            $newData[$attr] = $newData['reg_num'] ? round($val/$newData['reg_num'] * 100, 2) : 0;
        }
        
        unset($newData['reg_num']);
        $newData = array_values($newData);
        
        return $newData ?: [];
    }

    public static function remainChartDate($cond= []){
        if (is_numeric($cond['start'])) {
            $cond['start'] = date('Y-m-d', $cond['start']);
        }
        $start = $cond['start'] ?$cond['start']: date("Y-m-d", strtotime('-8 day'));

        if (is_numeric($cond['end'])) {
            $cond['end'] = date('Y-m-d', $cond['end']);
        }
        $end = $cond['end'] ?$cond['end']: date("Y-m-d", strtotime('-1 day'));

        return ['start' => $start, 'end' => $end];
    }

}
